package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.BaseEntity;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.CacheConstants.ALL_PRODUCT_KEY;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-28
 */
@SuppressWarnings("unchecked")
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Integer id) {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Integer[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Integer id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置查询条数
        listProductsRequest.setLimit(50);
        //查询
        ListProductsResponse listProductsResponse = client.listProducts(listProductsRequest);
        if (listProductsResponse.getHttpStatusCode() != 200) {
            throw new BaseException("请求华为云失败");
        }
        //得到查询数据
        List<ProductSummary> products = listProductsResponse.getProducts();

        //把查询数据拷贝到
        List<ProductVo> productVoList = BeanUtil.copyToList(products, ProductVo.class);
        //noinspection unchecked
        redisTemplate.opsForValue().set(ALL_PRODUCT_KEY, productVoList);
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中获取封装到对象中直接返回
        List<ProductVo> productVoList = (List<ProductVo>) redisTemplate.opsForValue().get(ALL_PRODUCT_KEY);
        return productVoList;
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        extracted(deviceDto);
        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.withBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        log.info("物联网接口 - 注册设备，调用成功");
        Device build = Device.builder().secret(response.getAuthInfo().getSecret()).build();
        BeanUtil.copyProperties(deviceDto, build);
        build.setIotId(response.getDeviceId());
        try {
            save(build);
            log.info("数据库新增成功");
        } catch (Exception e) {
            DeleteDeviceRequest deviceRequest = new DeleteDeviceRequest();
            deviceRequest.withDeviceId(response.getDeviceId());
            client.deleteDevice(deviceRequest);
            throw new BaseException("数据库新增异常");
        }
    }


    /**
     * 删除设备
     *
     * @param
     * @return
     */
    @Override
    public void reqisDelete(String iotId) {
        Device one = lambdaQuery().eq(Device::getIotId, iotId).one();
        //创建请求对象删除华为云
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        client.deleteDevice(request);

        log.warn("删除设备成功");
        this.deleteDeviceById(one.getId());


    }

    /**
     * 根据id查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceByIotId(String iotId) {
        Device one = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (ObjectUtil.isEmpty(one)) {
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.copyProperties(one, DeviceDetailVo.class);

        //查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        //设备状态
        String status = response.getStatus();
        deviceDetailVo.setDeviceStatus(status);

        //设备时间
        String activeTime = response.getActiveTime();
        if (ObjectUtil.isNull(activeTime)) {
            deviceDetailVo.setActiveTime(null);
            return deviceDetailVo;
        }
        //时区转换
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
        LocalDateTime localDateTime = parse.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        deviceDetailVo.setActiveTime(localDateTime);
        log.info("查询详情成功");
        return deviceDetailVo;
    }

    @Override
    public void updeteDevice(DeviceDto deviceDto) {
        Device device = new Device();
        BeanUtil.copyProperties(deviceDto, device);

        //修改华为云设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.iotId);
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.withBody(body);

        //正式修改
        client.updateDevice(request);
        log.info("修改设备成功");
        updateById(device);
    }

    /**
     * 查看设备上报的数据
     *
     * @return
     */
    @Override
    public ArrayList<Map<String, Object>> getQueryServiceProperties(String iotId) {
        //查询设备详情
        ShowDeviceShadowRequest showDeviceShadowRequest = new ShowDeviceShadowRequest();
        showDeviceShadowRequest.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(showDeviceShadowRequest);
        List<DeviceShadowData> response = showDeviceShadowResponse.getShadow();

        if (ObjectUtil.isEmpty(response)) {
            throw new BaseException("设备不存在数据");
        }

        DeviceShadowProperties reported = response.get(0).getReported();
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(reported.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        ArrayList<Map<String, Object>> data = new ArrayList<>();
        JSONUtil.parseObj(reported.getProperties()).forEach((k, v) -> {
            Map<String, Object> serviceProperties = new HashMap<>();
            serviceProperties.put("functionId", k);
            serviceProperties.put("value", v);
            serviceProperties.put("eventTime", eventTime);
            data.add(serviceProperties);
        });
        return data;

    }





    private void extracted(DeviceDto deviceDto) {
        if (ObjectUtil.isNull(deviceDto.getPhysicalLocationType())) {
            deviceDto.setPhysicalLocationType(-1);
        }
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        Long count1 = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count1 > 0) {
            throw new BaseException("设备编号重复");
        }
        Long count2 = lambdaQuery().eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()).eq(Device::getBindingLocation, deviceDto.getBindingLocation()).eq(Device::getProductKey, deviceDto.getProductKey()).count();
        if (count2 > 0) {
            throw new BaseException("位置|老人已存在设备");
        }
    }
}
